<template>
  <d2-container class="page">
    <el-dialog
      :visible.sync="dialogVisible4HeX"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="核销会员卡"
      width="1024px"
    >
      <el-row>
        <el-col :span="24">卡号:
          <el-input v-model="form.cardNo" style="width:250px" size="mini"></el-input>&nbsp;
          <el-button type="primary" @click="handleCreateNew('form')" size="mini">搜索</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table
            stripe
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>-->
            <el-table-column label="类型" width="120">
              <template slot-scope="scope">{{ scope.row.cartType }}</template>
            </el-table-column>
            <el-table-column label="使用方式">
              <template slot-scope="scope">{{ scope.row.usageModeName }}</template>
            </el-table-column>
            <el-table-column label="卡号" width="150">
              <template slot-scope="scope">{{ scope.row.cardNo }}</template>
            </el-table-column>
            <el-table-column label="客户">
              <template slot-scope="scope">{{ scope.row.realName }}</template>
            </el-table-column>
            <el-table-column label="手机" width="120">
              <template slot-scope="scope">{{ scope.row.mobile }}</template>
            </el-table-column>
            <el-table-column label="计次">
              <template slot-scope="scope">{{ scope.row.count }}</template>
            </el-table-column>
            <el-table-column label="市场价(元)" width="100">
              <template slot-scope="scope">{{ scope.row.price }}</template>
            </el-table-column>
            <el-table-column label="折扣价(元)" width="100">
              <template slot-scope="scope">{{ scope.row.discountPrice }}</template>
            </el-table-column>
            <el-table-column label="开始时间">
              <template slot-scope="scope">{{ scope.row.startDate | parseTime('{y}-{m}-{d}') }}</template>
            </el-table-column>
            <el-table-column label="结束时间">
              <template slot-scope="scope">{{ scope.row.endDate | parseTime('{y}-{m}-{d}') }}</template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template
                slot-scope="scope"
              >{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
            </el-table-column>
            <el-table-column label="更新时间" width="180">
              <template
                slot-scope="scope"
              >{{ scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
            </el-table-column>
            <el-table-column label="备注">
              <template slot-scope="scope">{{ scope.row.remarks }}</template>
            </el-table-column>
            <el-table-column label="销售">
              <template slot-scope="scope">{{ scope.row.remarks }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="showEditDlg(scope.row)"
                  icon="el-icon-edit"
                ></el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  icon="el-icon-delete"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <el-dialog
      :title="createOrEdit"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" ref="form">
        <el-form-item label="类型" :label-width="formLabelWidth" prop="name">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in options4carType"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用方式" :label-width="formLabelWidth" prop="name">
          <el-select v-model="form.usageMode" placeholder="请选择">
            <el-option
              v-for="item in options4usageMode"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡号" :label-width="formLabelWidth">
          <el-input v-model="form.cardNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价" :label-width="formLabelWidth">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" :label-width="formLabelWidth">
          <el-input v-model="form.discountPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="客户" :label-width="formLabelWidth" prop="name">
          <el-select v-model="form.customer" placeholder="请选择" filterable>
            <el-option
              v-for="item in options4Customer"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计次" :label-width="formLabelWidth">
          <el-input v-model="form.count" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择日期时间"
            value-format=" yyyy-MM-dd"
            format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="formLabelWidth" prop="name">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择日期时间"
            value-format=" yyyy-MM-dd"
            format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remarks" :rows="2" placeholder="请输入内容" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="销售" :label-width="formLabelWidth" prop="name">
          <el-select v-model="form.salesId" placeholder="请选择" filterable>
            <el-option
              v-for="item in options4Salses"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateNew('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-button type="primary" size="mini" @click="showCreateDlg('form')">新建</el-button>
    <el-button type="primary" size="mini" @click="getList()">刷新</el-button>
    <el-button type="primary" size="mini" @click="dialogVisible4HeX = true">核销</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>-->
      <el-table-column label="类型" width="120">
        <template slot-scope="scope">{{ scope.row.cartType }}</template>
      </el-table-column>
      <el-table-column label="使用方式">
        <template slot-scope="scope">{{ scope.row.usageModeName }}</template>
      </el-table-column>
      <el-table-column label="卡号" width="120">
        <template slot-scope="scope">{{ scope.row.cardNo }}</template>
      </el-table-column>
      <el-table-column label="客户">
        <template slot-scope="scope">{{ scope.row.realName }}</template>
      </el-table-column>
      <el-table-column label="手机" width="120">
        <template slot-scope="scope">{{ scope.row.mobile }}</template>
      </el-table-column>
      <el-table-column label="计次">
        <template slot-scope="scope">{{ scope.row.count }}</template>
      </el-table-column>
      <el-table-column label="市场价(元)" width="100">
        <template slot-scope="scope">{{ scope.row.price }}</template>
      </el-table-column>
      <el-table-column label="折扣价(元)" width="100">
        <template slot-scope="scope">{{ scope.row.discountPrice }}</template>
      </el-table-column>
      <el-table-column label="开始时间" width="100">
        <template slot-scope="scope">{{ scope.row.startDate | parseTime('{y}-{m}-{d}') }}</template>
      </el-table-column>
      <el-table-column label="结束时间" width="100">
        <template slot-scope="scope">{{ scope.row.endDate | parseTime('{y}-{m}-{d}') }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="200">
        <template
          slot-scope="scope"
        >{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column>
      <el-table-column label="更新时间" width="200">
        <template
          slot-scope="scope"
        >{{ scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">{{ scope.row.remarks }}</template>
      </el-table-column>
      <el-table-column label="销售">
        <template slot-scope="scope">{{ scope.row.salesName }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showEditDlg(scope.row)" icon="el-icon-edit"></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination background="" layout="prev, pager, next" :total="50"></el-pagination>
  </d2-container>
</template>

<script>
import {
  fetchList,
  createOrEdit,
  queryById,
  deleteById
} from "@/api/sys.membership";

import * as dict from "@/api/sys.dict";
import * as user from "@/api/sys.user";

export default {
  components: {},
  data() {
    return {
      dialogVisible4HeX: false,

      options4Salses: [],
      options4usageMode: [],
      options4Customer: [],
      options4carType: [],

      fileList: [],
      tableData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        type: null,
        price: null,
        customer: null,
        count: null,
        remarks: null,
        startDate: null,
        endDate: null,
        usageMode: null,
        cardNo: null,
        discountPrice: null,
        salesId: null
      },
      formLabelWidth: "100px",
      dialogImageUrl: "",
      dialogVisible: false,
      createOrEdit: "",
      downloadPath: ""
    };
  },
  mounted() {
    this.getList();

    dict.fetchList("{parentCode: 'cardType'}").then(resp => {
      this.options4carType = resp.data;
    });

    dict.fetchList("{parentCode: 'usageMode'}").then(resp => {
      this.options4usageMode = resp.data;
    });

    user.userList().then(resp => {
      this.options4Customer = resp.data;
      this.options4Customer.forEach(element => {
        if (element.nickName != null)
          element.name = element.realName + " (" + element.mobile + ")";
      });
    });

    user.queryUserListByRole({roleId: 3}).then(resp => {
      this.options4Salses = resp.data;
      this.options4Salses.forEach(element => {
        if (element.nickName != null)
          element.name = element.realName + " (" + element.mobile + ")";
      });
    });
  },

  filters: {
    parseTime: function(time, cFormat) {
      time = Date.parse(new Date(time));
      if (arguments.length === 0) {
        return null;
      }

      if ((time + "").length === 10) {
        time = +time * 1000;
      }

      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        date = new Date(parseInt(time));
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a")
          return ["一", "二", "三", "四", "五", "六", "日"][value - 1];
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return timeStr;
    }
  },

  methods: {
    showCreateDlg(formName) {
      this.dialogFormVisible = true;
      this.createOrEdit = "新建";
      // this.$refs[formName].resetFields();
    },

    showEditDlg(row) {
      this.dialogFormVisible = true;
      this.createOrEdit = "编辑";
      this.form = row;
      this.fileList = [{ url: row.photographList[0] }];
      this.downloadPath = row.photographList[0];
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.success) this.downloadPath = response.downloadPath;
    },

    handleCreateNew(formName) {
      let that = this;

      const set = that.$refs;
      set[formName].validate(valid => {
        if (valid) {
          createOrEdit(that.form).then(() => {
            that.dialogFormVisible = false;
            that.getList();
            that.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },

    getList() {
      fetchList(this.listQuery).then(response => {
        if (response.success) this.tableData = response.data;
      });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleDelete(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteById(row.id)
          .then(() => {
            this.getList();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .catch(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.page {
  .logo {
    width: 120px;
  }
  .btn-group {
    color: $color-text-placehoder;
    font-size: 12px;
    line-height: 12px;
    margin-top: 0px;
    margin-bottom: 20px;
    .btn-group__btn {
      color: $color-text-sub;
      &:hover {
        color: $color-text-main;
      }
      &.btn-group__btn--link {
        color: $color-primary;
      }
    }
  }
}
</style>
